package com.aier.user.service.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

import com.aier.common.common.Constant;
import com.aier.common.dao.ICommonDAO;
import com.aier.user.entity.Follow;
import com.aier.user.entity.FollowGroup;
import com.aier.user.entity.mapper.FollowGroupRowMapper;
import com.aier.user.entity.mapper.FollowRowMapper;
import com.aier.user.entity.mapper.FreshRowMapper;
import com.aier.user.entity.mapper.FriendRowMapper;
import com.aier.user.entity.mapper.LetterRowMapper;
import com.aier.user.service.IMyFollowService;

@Component("myFollowService")
public class MyFollowServiceImpl_J implements IMyFollowService {

	@Resource(name = "commonDao")
	private ICommonDAO commonDao;

	public void setCommonDao(ICommonDAO commonDao) {
		this.commonDao = commonDao;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<FollowGroup> searchFollowGroup(Long uid) {

		return (List<FollowGroup>) commonDao
				.list("select 0 as fgid, uid, '特别关注' as name, cdate, count(*) as count from follow where uid = ? and fgid = 0 union "
						+ "select fg.*, ( select count(*) from follow where fgid = fg.fgid ) as count from follow_group fg where fg.uid = ? union "
						+ "select - 1 as fgid, uid, '未分组' as name, cdate, count(*) as count from follow where uid = ? and fgid =-1",
						new Object[] { uid, uid, uid },
						new FollowGroupRowMapper());
	}

	@Override
	public Map<String, Object> searchAllFollow(int page, int pagesize,
			Long uid, Long fgid, String sort, Short state) {
		String sql = "select f.*,u.nickname,u.headimg,u.desinfo,fg.`name` as fgname,"
				+ "(select count(*) from follow where fuid = u.uid) as cfans from follow f "
				+ "left join `user` u on f.fuid = u.uid left join follow_group fg "
				+ "on fg.fgid = f.fgid where f.uid=?";
		List<Object> largcount = new ArrayList<Object>();
		largcount.add(uid);
		if (null != fgid) {
			sql += " and f.fgid = ?";
			largcount.add(fgid);
		}
		if (null != state && state != 0) {
			sql += " and f.state = ?";
			largcount.add(state);
		}
		if ("cfans".equals(sort)) {
			sql += " order by cfans desc";
		} else {
			sql += " order by f.cdate desc";
		}

		return commonDao.queryPage(sql, page, pagesize, largcount,
				new FollowRowMapper(FollowRowMapper.FOLLOW_BRIEF));
	}

	@Override
	public int deleteFollow(Long uid, String fuidStr) {
		if (null != fuidStr && !"".equals(fuidStr)) {
			for (String fuid : fuidStr.split(",")) {
				commonDao.update(
						"delete from follow where uid = ? and fuid = ?",
						new Object[] { uid, fuid });
				if (null != commonDao.listByObject(
						"select * from friend where uid=? and auid=?",
						new Object[] { uid, fuid }, new FriendRowMapper())) {
					commonDao.update(
							"delete from friend where uid = ? and auid = ?",
							new Object[] { uid, fuid });
				}
				commonDao.update(
						"update follow set state = 1 where uid=? and fuid=?",
						new Object[] { fuid, uid });

			}
		}
		return 1;
	}

	@Override
	public int insertFollow(Long uid, Long fuid) {
		// 已存在关注
		int i = 0;

		if (null != commonDao.listByObject(
				"select * from follow where uid = ? and fuid = ?",
				new Object[] { uid, fuid }, new FollowRowMapper())) {
			// commonDao.update("update follow set state = 2 where uid=? and fuid=?",new
			// Object[]{fuid,uid});
			// commonDao.update("update letter set state = 1 where suid=? and ruid=? and type = 4",new
			// Object[]{fuid,uid});
			i=1;
			return i;
		}
		String nickname = (String) commonDao.listByObject(
				"select nickname from user where uid=?", new Object[] { uid },
				new RowMapper<String>() {
					@Override
					public String mapRow(ResultSet rs, int arg1)
							throws SQLException {
						return rs.getString("nickname");
					}
				});
		// 如果对方是你的粉丝，修改状态为互相关注
		if (null != commonDao.listByObject(
				"select * from follow where uid=? and fuid=?", new Object[] {
						fuid, uid }, new FollowRowMapper())) {
			commonDao.update(
					"update follow set state = 2 where uid=? and fuid=?",
					new Object[] { fuid, uid });
			commonDao
					.update("insert into follow(uid,fuid,fgid,state,remark,cdate) values(?,?,?,?,?,?)",
							new Object[] { uid, fuid, -1, 2, "",
									new Timestamp(new Date().getTime()) });

			// 如果有关注邀请，修改状态为已处理
			// if (null !=
			// commonDao.list("select * from letter where suid = ? and ruid = ? and type = 4 and rdel = 0 and state = 0",
			// new Object[]{fuid,uid},new LetterRowMapper())) {
			// commonDao.update("update letter set state = 1 where suid=? and ruid=? and type = 4",new
			// Object[]{fuid,uid});
			// i=2;
			// // 发私信

			commonDao
					.update("insert into letter(suid,ruid,type,content,state,sdel,rdel,img,cdate) values(?,?,?,?,?,?,?,?,?)",
							new Object[] { uid, fuid, Constant.num_5,
									"你好，你与@" + nickname + " 已经成为好友.", 0, 0, 0,
									null, new Timestamp(new Date().getTime()) });
			// }
			i=1;
		} else {
			commonDao
					.update("insert into follow(uid,fuid,fgid,state,remark,cdate) values(?,?,?,?,?,?)",
							new Object[] { uid, fuid, -1, 1, "",
									new Timestamp(new Date().getTime()) });
			commonDao
					.update("insert into letter(suid,ruid,type,content,state,sdel,rdel,img,cdate) values(?,?,?,?,?,?,?,?,?)",
							new Object[] { uid, fuid, Constant.num_5,
									"你好，@" + nickname + " 关注了你.", 0, 0, 0,
									null, new Timestamp(new Date().getTime()) });
			i=1;
		}
		return i;
	}

	@Override
	public int updateFollowGroup(Long uid, String fuidStr, Long fgid) {
		if (null != fuidStr && !"".equals(fuidStr)) {
			for (String fuid : fuidStr.split(",")) {
				commonDao.update(
						"update follow set fgid=? where uid=? and fuid = ?",
						new Object[] { fgid, uid, fuid });
			}
		}
		return 1;
	}

	@Override
	public int insertFollowGroup(Long uid, String name) {
		// 已存在相同分组
		if (null != commonDao.listByObject(
				"select * from follow_group where uid=? and name=?",
				new Object[] { uid, name }, new FollowGroupRowMapper())) {
			return Constant.num_10001;
		}
		return commonDao
				.update("insert into follow_group(uid,name,cdate) values(?,?,?)",
						new Object[] { uid, name,
								new Timestamp(new Date().getTime()) });
	}

	@Override
	public int insertRFLetter(Long uid, Long ruid, String content) {
		// 发私信
		String nickname = (String) commonDao.listByObject(
				"select nickname from user where uid=?", new Object[] { uid },
				new RowMapper<String>() {
					@Override
					public String mapRow(ResultSet rs, int arg1)
							throws SQLException {
						return rs.getString("nickname");
					}
				});
		return commonDao
				.update("insert into letter(suid,ruid,type,content,state,sdel,rdel,img,cdate) values(?,?,?,?,?,?,?,?,?)",
						new Object[] { uid, ruid, Constant.num_4,
								"@" + nickname + " 邀请您关注他。" + content, 0, 0, 0,
								null, new Timestamp(new Date().getTime()) });
	}

	@Override
	public Map<String, Object> searchFreshByFgid(int page, int page_size,
			Long uid, Long fgid) {
		String sql = "select f.*,UNIX_TIMESTAMP(f.cdate)*1000 as stamp, u.nickname, u.headimg as headimg from fresh f left join `user` u "
				+ "on u.uid = f.uid where ( f.power = 0 or ( f.power = 3 and f.uid in ( select fo.fuid from follow fo where fo.uid = ? "
				+ "and fo.fgid = f.fgid )) or ( f.power = 1 and f.uid in ( select fr.auid from friend fr where fr.uid = ? ))) and f.uid in "
				+ "( select fuid from follow where uid = ? and fgid = ? ) order by f.cdate desc";

		return commonDao.queryPage(sql, page, page_size, new Object[] { uid,
				uid, uid, fgid }, new FreshRowMapper());
	}

	@Override
	public Map<String, Object> searchFollowDo(int page, int pagesize, Long uid,
			Long fgid) {
		String sql = "select f.*,u.nickname,u.headimg,us.nickname as fnickname,us.headimg as fheadimg from follow f left join user u "
				+ "on u.uid = f.uid left join user us on us.uid = f.fuid where f.uid in (select fuid from follow where uid = ? and fgid = ?) and "
				+ "f.uid not in (select auid from friend where uid = ?) and f.fuid !=? order by cdate desc";
		return commonDao.queryPage(sql, page, pagesize, new Object[] { uid,
				fgid, uid, uid },
				new FollowRowMapper(FollowRowMapper.FOLLOW_DO));
	}

	@Override
	public int searchFollowByUid(Long uid, Long fuid) {
		if (null == commonDao.listByObject(
				"select * from follow where uid = ? and fuid = ?",
				new Object[] { uid, fuid }, new FollowRowMapper())) {
			return 0;
		} else {
			return 1;
		}

	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Follow> searchFollowForSpecial(Long uid) {
		return (List<Follow>) commonDao
				.list("select f.*,u.nickname from follow f left join user u on u.uid = f.fuid where f.uid = ? "
						+ "order by f.cdate", new Object[] { uid },
						new FollowRowMapper());

	}

	@Override
	public Map<String, Object> searchAllFriend(int page, int pagesize,
			Long uid, Short state) {
		String sql = "";
		if (state == 1 || state == 2) {
			sql = "select f.*,u.headimg,u.nickname,u.sex,u.address,if(birthday is not null,year(now())-year(birthday),null) as age,u.account,"
					+ "(case when ct.cid in (select cid from class_teacher ct left join school_teacher st on ct.tid = st.tid where uid = ?) then 1 else 0 end) as st,"
					+ "(case when cp.cid in (select distinct (cid) from class_parent cp where cp.uid = ?) then 1 else 0 end) as sc,"
					+ "(case when st.sid in (select sid from school_teacher where uid = ?) then 2 else 0 end) as ss"
					+ " from follow f "
					+ " left join `user` u on f.fuid = u.uid"
					+ " left join `class_parent` cp on cp.uid = u.uid "
					+ " left join `school_teacher` st on st.uid = u.uid"
					+ " left join `class_teacher` ct on ct.tid = st.tid"
					+ " where f.uid = ? and f.state = ?  group by u.uid order by f.cdate asc ";
			return commonDao.queryPageThree(sql, page, pagesize, new Object[] {
					uid, uid, uid, uid, state }, new FollowRowMapper(
					FollowRowMapper.FOLLOW_FRIEND));

		} else {
			sql = "select f.foid,f.uid,f.fuid,f.state,f.cdate,u.headimg,u.nickname,u.sex,u.address,if(birthday is not null,year(now())-year(birthday),null) as age,u.account,"
					+ "(case when ct.cid in (select cid from class_teacher ct left join school_teacher st on ct.tid = st.tid where uid = ?) then 1 else 0 end) as st,"
					+ "(case when cp.cid in (select distinct (cid) from class_parent cp where cp.uid = ?) then 1 else 0 end) as sc,"
					+ "(case when st.sid in (select sid from school_teacher where uid = ?) then 2 else 0 end) as ss"
					+ " from follow f "
					+ " left join `user` u on f.uid = u.uid"
					+ " left join `class_parent` cp on cp.uid = u.uid "
					+ " left join `school_teacher` st on st.uid = u.uid"
					+ " left join `class_teacher` ct on ct.tid = st.tid"
					+ " where f.fuid = ? and f.state = 1   group by u.uid order by f.cdate desc ";
			return commonDao.queryPageFour(sql, page, pagesize, new Object[] {
					uid, uid, uid, uid }, new FollowRowMapper(
					FollowRowMapper.FOLLOW_FRIEND));
		}

	}

	@Override
	public Follow searchFriend(Long uid, Long fuid) {
		String sql = "select * from  follow where uid =? and fuid = ? ";
		return (Follow) commonDao.listByObject(sql, new Object[] { uid, fuid },
				new FollowRowMapper());
	}

}
